<template>
  <!-- 运行监测 -->
  <div class="topContent">
    <div class="topBar">
      <a-radio-group v-model:value="imgType" @change="changeWiringDiagram">
        <a-radio-button :value="1">拓扑图</a-radio-button>
        <a-radio-button :value="2" v-has="['wiringDiagram']"
          >一次接线图</a-radio-button
        >
        <a-radio-button :value="3" :disabled="!networkDiagramUrl"
          >组网图</a-radio-button
        >
      </a-radio-group>
      <!-- <div class="zoomVal">
        <a-slider
          v-model:value="zoomVal"
          :disabled="disabled"
          max="200"
          :marks="marks"
        />
        <a-button type="link" @click="zoomBack" class="zoomBack"
          >还原比例</a-button
        >
      </div> -->
    </div>
    <!-- <div class="status normal">
      <span class="statusIcon" />
      正常
    </div> -->
    <div class="canvasOutContent">
      <a-spin :spinning="loading" size="large">
        <DrawingCanvas
          v-if="imgType === 1"
          ref="canvasOutContent"
          :rowData="rowData"
          :topologyMap="topologyMap"
          :stationInfo="stationInfo"
          :stationDataInfo="stationDataInfo"
          @handleSaveDragConfig="handleSaveDragConfig"
          @getElements="getElements"
          :style="{ zoom: zoomVal / 100 }"
        />
        <div v-if="imgType === 2 && wiringDiagramUrl" class="wiringDiagramUrl">
          <div v-if="wiringDiagramUrlExt === 'pdf'">
            <iframe
              :src="wiringDiagramUrl"
              height="900px;"
              width="100%"
            ></iframe>
          </div>
          <img :src="wiringDiagramUrl" v-else />
        </div>
        <div v-if="imgType === 3 && networkDiagramUrl" class="wiringDiagramUrl">
          <div v-if="networkDiagramUrlExt === 'pdf'">
            <iframe
              :src="networkDiagramUrl"
              height="900px;"
              width="100%"
            ></iframe>
          </div>
          <img :src="networkDiagramUrl" v-else />
        </div>
      </a-spin>
    </div>
  </div>
</template>
<script setup>

import DrawingCanvas from "./conpoments/DrawingCanvas.vue";
import { EQUIP_TYPE } from "@/constants/stationConfig";

const props = defineProps({
  stationInfo: {
    type: Number,
  },
  stationDataInfo: {
    type: Array,
  },
});
const isWiringDiagramUrl = ref(false);
const imgType = ref(1);
const $api = inject("$api");
const topologyMap = ref([]); // 拓扑图前端回显数据
const loading = ref(false);
const zoomVal = ref(100);
const marks = ref({
  0: "0%",
  100: "100%",
  200: "200%",
});
const getStationTopologyMapDetails = async (stationId) => {
  // 查询拓扑图
  const res = await $api.stationTopologyMapDetails(stationId);
  if (res && res.code === 0) {
    topologyMap.value = res?.data?.topologyMap || [];
    if (topologyMap.value.length) {
      const topologyMapData = JSON.parse(topologyMap.value);

      // 处理储充项目(充电桩)
      const chargingItems = topologyMapData.data.filter(
        (item) => item.type === EQUIP_TYPE.CHONG_DIAN_ZHUANG
      );
      if (chargingItems.length > 0) {
        const chargingPromises = chargingItems.map(async (item) => {
          if (item.systemId) {
            try {
              const res = await $api.getChargingIds(item.systemId);
              if (res && res.code === 0) {
                item.blockNameId1 = res.data?.blockIds[0];
                item.blockNameId2 = res.data?.blockIds[1];
                item.chargeId1 = res.data?.chargingGunId[0];
                item.chargeId2 = res.data?.chargingGunId[1];
                item.linkId = res.data?.linkId;
              }
            } catch (error) {
              console.error("获取充电桩数据失败", error);
            }
          }
        });
        await Promise.all(chargingPromises);
      }
      return topologyMapData;
    }
  }
};
const changeWiringDiagram = async () => {
  topologyMap.value = [];
  if (imgType.value === 1) {
    await nextTick();
    //getStationTopologyMapDetails(props.stationInfo.id);
    handleChageStation();
  }
};
const getStationTopologyMapRealtime = async (stationId) => {
  // 查询拓扑图上的实时数据
  const res = await $api.stationTopologyMapRealtime(stationId);
  if (res?.code !== 0) {
    return;
  }
  return res.data;
};
const getStationRealtimeWarn = async (linkId, topologyMapData) => {
  // 查询告警信息
  const res = await $api.realtimeWarn(linkId);
  if (res?.code !== 0) {
    return;
  }
  return res.data;
};
const getCommonAssertCode = async (linkId) => {
  const res = await $api.commonAssertCode(linkId);
  if (res?.code !== 0) {
    return;
  }
  return res.data;
};
const wiringDiagramUrl = ref("");
const wiringDiagramUrlExt = ref("");
const getStationWiringDiagramUrl = async () => {
  // 查询一次接线图url
  const res = await $api.stationWiringDiagramUrl(props.stationInfo.id);

  wiringDiagramUrl.value = res.data;
  // 获取URL的后缀名
  wiringDiagramUrlExt.value = wiringDiagramUrl.value?.split(".").pop() || "";
};
const networkDiagramUrl = ref("");
const networkDiagramUrlExt = ref("");
const getStationNetworkDiagramUrl = async () => {
  // 查询一次组网图url
  const res = await $api.stationNetworkDiagramUrl(props.stationInfo.id);

  networkDiagramUrl.value = res.data;
  // 获取URL的后缀名
  networkDiagramUrlExt.value = networkDiagramUrl.value?.split(".").pop() || "";
};
const canvasOutContent = ref(null);
const handleBack = () => {
  canvasOutContent.value.handleBack();
};
const getStationTopologyMapLinkStatus = async (stationId) => {
  // 查询电池堆状态数据
  const res = await $api.stationTopologyMapLinkStatus(stationId);
  if (res?.code !== 0) {
    return;
  }
  return res.data;
};

const handleChageStation = async () => {
  topologyMap.value = [];
  loading.value = true;
  Promise.all([
    getStationTopologyMapDetails(props.stationInfo.id),
    // getStationTopologyMapLinkStatus(props.stationInfo.id),
    getStationTopologyMapRealtime(props.stationInfo.id),
    getStationRealtimeWarn(props.stationInfo.id),
    getCommonAssertCode(props.stationInfo.id),
  ]).then(([mapData, realTimeData, warnData, commonAssertCode]) => {
    // mapData 拓扑图数据
    // props.stationDataInfo 电池堆状态数据
    // warnData 告警数据
    // realTimeData 实时数据
    loading.value = false;
    if (!mapData) {
      // 无数据直接返回
      return;
    }
    const topologyMapData = mapData;
    const deviceStatus = {}; // 电站状态

    if (props.stationDataInfo?.length) {
      for (const item of props.stationDataInfo) {
        deviceStatus[item.deviceId] = {
          lineStatus: item.lineStatus,
          warnNum: item.warnNum,
        };
      }
    }
    for (const item of topologyMapData?.data) {
      // 将实时数据塞入topologyMap拓扑图数据中
      if (realTimeData && Object.keys(realTimeData).length) {
        if (item.systemId) {
          // 变压器和并网柜的实时数据，挂到对应的关口表、并网表上
          if (
            item.type !== EQUIP_TYPE.BIAN_YA_QI &&
            item.type !== EQUIP_TYPE.BING_WANG_GUI
          ) {
            item.infoData = realTimeData[item.systemId];
          }
          item.linkElectronStatus = realTimeData[item.systemId]?.find(
            (realData) => realData.name === "linkElectronStatus"
          )?.value;
        }
        if (
          (item.type === EQUIP_TYPE.GUAN_KOU_BIAO ||
            item.type === EQUIP_TYPE.BING_WANG_BIAO) &&
          item.isChildEquip
        ) {
          item.infoData = realTimeData[item.parentId];
        }
      }

      // 将电池堆状态数据塞入topologyMap拓扑图数据中
      if (item.systemId) {
        const status = deviceStatus[item.systemId];
        if (status) {
          item.lineStatus = status.lineStatus;
        }
      }
      // 将告警数据塞入topologyMap拓扑图数据中
      if (item.systemId && warnData?.length) {
        item.warnData = warnData?.find(
          (warn) => warn.deviceId === item.systemId
        );
      }

      // 将资产数据塞入topologyMap拓扑图数据中
      if (commonAssertCode?.length) {
        let assertCodeData = null;
        if (item.isChildEquip === 1) {
          assertCodeData = commonAssertCode?.find(
            (assert) => assert.deviceId === item.parentId
          );
        } else {
          assertCodeData = commonAssertCode?.find(
            (assert) => assert.deviceId === item.systemId
          );
        }

        if (assertCodeData) {
          item.assertCodeData = assertCodeData;
        }
      }

      // 充电桩数据组装
      if (item.type === EQUIP_TYPE.CHONG_DIAN_ZHUANG) {
        // 处理实时数据
        if (realTimeData && Object.keys(realTimeData).length) {
          item.blockNameInfo1 = realTimeData[item.blockNameId1];
          item.blockNameInfo2 = realTimeData[item.blockNameId2];
          item.chargeInfo1 = realTimeData[item.chargeId1];
          item.chargeInfo2 = realTimeData[item.chargeId2];
          item.linkInfo = realTimeData[item.linkId];
          item.linkElectronStatus = realTimeData[item.linkId]?.find(
            (realData) => realData.name === "linkElectronStatus"
          )?.value;
        }
        // 处理告警数据
        if (item.systemId && warnData?.length) {
          item.warnData = warnData?.find(
            (warn) => warn.deviceId === item.linkId
          );
        }
        // 充电桩资产编码，分为簇1和簇2
        if (item.blockNameId1 && commonAssertCode?.length) {
          const assertCodeData = commonAssertCode?.find(
            (assert) => assert.deviceId === item.blockNameId1
          );
          if (assertCodeData) {
            item.assertCodeData1 = assertCodeData;
          }
        }
        if (item.blockNameId2 && commonAssertCode?.length) {
          const assertCodeData = commonAssertCode?.find(
            (assert) => assert.deviceId === item.blockNameId2
          );
          if (assertCodeData) {
            item.assertCodeData2 = assertCodeData;
          }
        }
      }
      // 集装箱项目数据组装
      if (item.type === EQUIP_TYPE.JI_ZHUANG_XIANG) {
        // 集装箱
        item.infoData = realTimeData?.[item.systemId];
        // 集装箱的电池簇
        item.children.forEach((child) => {
          child.infoData = realTimeData?.[child.systemId];
        });
        // 处理告警数据
        // const wwarnData = [
        //   {
        //     deviceId: 15,
        //     warnNumber: 1,
        //     evtInfoId: 2488051,
        //     pdId: 134799,
        //     warnMessage: "空调通信故障",
        //   },
        // ];
        if (item.systemId && warnData?.length) {
          item.warnData = warnData?.find(
            (warn) => warn.deviceId === item.systemId
          );
        }
      }
    }
    topologyMap.value = topologyMapData;
  });

  getStationWiringDiagramUrl(props.stationInfo.id);
  getStationNetworkDiagramUrl(props.stationInfo.id);
  canvasOutContent.value.handleChageStation();
};
const zoomBack = () => {
  zoomVal.value = 100;
};
onMounted(() => {
  // setInterval(() => {
  //   handleChageStation()
  //   console.log('[ handleChageStation ]-227')
  // }, 5000)
});

defineExpose({ handleBack, handleChageStation });
</script>

<style lang="less" scoped>
.ant-switch {
  margin: 0 30px 0 5px;
}
.status {
  display: inline-block;
  .statusIcon {
    display: inline-block;
    width: 6px;
    height: 6px;
    border-radius: 50%;
    margin-right: 5px;
    vertical-align: middle;
  }
}
.normal {
  color: green;
  .statusIcon {
    background-color: green;
  }
}
.canvasOutContent {
  width: calc(100vw - 250px);
  height: calc(100vh - 250px);
  border: 1px solid #ccc;
  overflow: auto;
  margin-top: 15px;
  position: relative;
  background-color: #202020;
}
.wiringDiagramUrl {
  max-width: 100%;
  img {
    width: 100%;
  }
}
.topBar {
  position: relative;
}
.zoomVal {
  width: 300px;
  position: absolute;
  right: 20px;
  top: -15px;
  .ant-slider {
    width: 200px;
    display: inline-block;
  }
  .zoomBack {
    vertical-align: top;
    position: relative;
    top: 5px;
    left: 5px;
  }
}
</style>
